import { ref } from "vue"
import { useBaseSearchForm } from "@/old-hooks/use-base-search-form"
import message from "@/utils/message";
import { exportExcel } from "@/utils/excel";
import { importTableFile } from "@/api/upload"
import { useStoreMgShopStore } from "@/store/storeMg/shop"
import { useStoreMgSettlementStore } from "@/store/storeMg/settlement"

export function useBasePageTable(storeName, basePageTableRef) {

    let map = new Map();

    // pinia
    let storeMgShopStore = useStoreMgShopStore()
    let storeMgSettlementStore = useStoreMgSettlementStore()

    // 存入到数组中
    let mapList = [storeMgShopStore, storeMgSettlementStore]

    // 根据storeName 查找对应的pinia
    const mapValue = mapList.find((item) => item.$id === storeName);

    // 存入到map
    map.set(storeName, mapValue);

    // 表格选中数据
    let selectList = ref([])

    // 表格多选hook
    const selectionChangeHook = (value) => {
        selectList.value = value
    }

    // 批量删除hook 
    const batchDeleteHook = () => {
        if (selectList.value.length === 0) {
            message.error("请选择需要删除的数据")
            return
        }
        deleteData(selectList.value)
    }

    // 删除hook
    const deleteHook = (row) => {
        deleteData([row])
    }

    // 删除表格数据方法
    const deleteData = (rows) => {
        message.confirm("此操作将删除选中的数据, 是否继续?", async (res) => {
            if (res) {
                map.get(storeName).deletePageTableData(rows).then(res => {
                    searchHook()
                }).catch(err => { })
            }
        });
    }

    // 导入hook
    const importHook = (url) => {
        // 创建上传input
        const input = document.createElement("input");
        input.type = "file";
        // 限制上传文件格式
        // input.accept = ".xlsx,.xls";
        input.click();

        input.onchange = async (e) => {
            const file = input.files?.[0];
            if (!file) return;
            const formData = new FormData();
            formData.append("file", file);
            try {
                // url 接口地址 formData文件流
                importTableFile(url, formData).then(res => {
                    message.success("导入成功");
                    // 重新刷新表格
                    searchHook();
                }).catch(err => {
                    message.error("导入失败");
                })
            } catch (err) {
                message.error("导入失败");
            }
        };
    }

    // 导出hook
    const exportHook = (data) => {
        data.sheetName = "sheetName"
        exportExcel(data.table, data.tableName, data.colHeaders, data.sheetName);
    }

    // base-search-form 查询表格数据hook
    const { searchHook } = useBaseSearchForm(basePageTableRef)

    return { selectionChangeHook, batchDeleteHook, deleteHook, importHook, exportHook }

}